#include "shell.h"

Shell::Shell(int limit, QObject *parent)
    : QObject(parent)
    , m_limit(limit)
{}

int Shell::size()
{
    size_t s = 0;
    m_mux.lock();
    s = m_shell.size();
    m_mux.unlock();
    return s;
}

int Shell::try_push_book()
{
    int s = -1;
    m_mux.lock();
    if (m_shell.size() != m_limit)
    {
        m_shell.push_back(true);
        s = m_shell.size() - 1;
        emit book_added(s);
    }
    m_mux.unlock();
    return s;
}

bool Shell::try_asquire_for_read(int pos)
{
    bool b = false;
    m_mux.lock();
    b = m_shell[pos];
    m_shell[pos] = false;
    m_mux.unlock();
    return b;
}

void Shell::try_asquire_for_write(int pos)
{
    m_mux.lock();
    while (!m_shell[pos]) m_con.wait(&m_mux);
    m_mux.unlock();
}

void Shell::release_book(int pos)
{
    m_mux.lock();
    m_shell[pos] = true;
    m_con.wakeAll();
    m_mux.unlock();
}
